const Model = require('./index')

class ResourceModel extends Model {
  async create (attrs) {
    const { parentId, type, name, code, sort } = attrs
    const createTime = this.dateFormat(new Date())
    const sql = `insert into resource (parentId, type, name, code, sort, createTime)
      values(?, ?, ?, ?, ?, ?)`
    try {
      await this.db.query(sql, [parentId, type, name, code, sort, createTime])
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 所有资源查询
   * @param {*} conditions
   * @returns
   */
  async find (conditions) {
    const conditionSql = this.generateWhereClause(conditions)
    const sql = `select * from resource ${conditionSql} order by sort asc`
    try {
      const data = await this.db.query(sql)
      return data
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 递归删除资源同时删除角色下存在的权限资源
   * @param {*} id
   */
  async delete (id) {
    const sql = `with recursive cte as 
      (select resource.id, resource.parentId from resource where resource.id = ?
      union all 
      select resource.id, resource.parentId from resource inner join cte on resource.parentId = cte.id) 
      delete resource, rp from resource
      left join role_permission rp on rp.permissionId = resource.id where resource.id in (select id from cte)`
    try {
      await this.db.query(sql, [id])
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 更新资源信息
   * @param {*} id
   * @param {*} attrs
   */
  async update (id, attrs) {
    let { name, parentId, sort, type, code } = attrs
    const { columnSet, values } = this.multipleColumnSet({
      name,
      sort,
      type,
      code
    })
    parentId = this.isNull(parentId) ? null : parentId
    const sql = `update resource set ${columnSet}, parentId = ? where id = ?`
    try {
      await this.db.query(sql, [...values, parentId, id])
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new ResourceModel('resource')
